using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class AIcontroller : MonoBehaviour {
	
	public float detectionAngle = 90f;
	
	private AStar pathfinder;
	public float distanceTollerance = 1f;
	
	public float turnSpeed = 1f;
	public float speed;
	public float maxVelocityChange = 1.0f;
	
	public bool debug = false;
	
	public float animationSpeed = 1f;
	
	private List<AStar.node> path = new List<AStar.node>();
	private AStar.node currentNode = null;
	
	
	
	// Use this for initialization
	void Start () {
		pathfinder = new AStar(transform.position);
	}
	

	
	// Update is called once per frame
	void Update () {
		if(Network.isClient){
			this.enabled = false;
		}
		
		if(path.Count==0){
			path = pathfinder.GetPath(transform.position);
			currentNode = path[path.Count-1];
			path.RemoveAt(path.Count-1);
			//Debug.Log(currentNode.pos);
		}
		if((transform.position-currentNode.pos).magnitude<distanceTollerance){
			if(path.Count>0){
				currentNode = path[path.Count-1];
				path.RemoveAt(path.Count-1);
				//Debug.Log(currentNode.pos);
			}
		}
		//Move!
		Quaternion rotation = Quaternion.LookRotation(currentNode.pos-transform.position,Vector3.up);
		transform.parent.rotation = Quaternion.Slerp(transform.parent.rotation,rotation,Time.deltaTime*turnSpeed);
		Vector3 direction = (currentNode.pos-transform.position).normalized;
		
		
		Vector3 targetVelocity = new Vector3(0,0,1);
		targetVelocity *= speed;
		Vector3  velocity = transform.parent.rigidbody.velocity;
		Vector3 velocityChange = (targetVelocity-velocity);
		velocityChange.x = Mathf.Clamp(velocityChange.x, -maxVelocityChange, maxVelocityChange);
	    velocityChange.z = Mathf.Clamp(velocityChange.z, -maxVelocityChange, maxVelocityChange);
	    velocityChange.y = 0;
		
		//transform.parent.rigidbody.AddForce(direction*speed, ForceMode.VelocityChange);
		transform.parent.rigidbody.MovePosition(transform.parent.position+transform.parent.forward*speed);
	}
	
void OnDrawGizmos()	{
		if(debug){
			//Debug.Log(path.Count);
			for(int i = 0;i<path.Count;i++){
				AStar.node n = path[i];
				if(n.parent != null){
					Gizmos.color = Color.red;
					Gizmos.DrawLine(path[i].pos,path[i].parent.pos);
				}
			}
		}
	}
	
	
	void OnTriggerEnter(Collider other){
		if(Network.isServer){
			if(Vector3.Angle(transform.forward,other.transform.position)<detectionAngle){
				if(other.gameObject.GetComponent<WeaponSystem>() !=null){
					transform.parent.GetComponentInChildren<Animation>()["Take 001"].speed = 1f;
					networkView.RPC("setAnimationSpeedRPC",RPCMode.Others,animationSpeed);
					AggroState arg = gameObject.GetComponent<AggroState>();
					arg.setTarget(other.gameObject);
					arg.setPursuit();
					this.enabled = false;
					gameObject.GetComponent<AggroState>().enabled = true;
				}
			}
		}
	}
	
}
